import { fetchDeliverySchools, getAllSchool, swichDefaultSchool, addStudent, setDefaultStudent } from '../../../services/students/studentData';
import { setSelectedSchoolId, getSchoolList, setSelectedSchoolData, getSelectedSchoolData, setStudentsList, getStudentsList, getSelectedSchoolId, setSelectedStudentId } from '../../../userData/userData';
import Toast from 'tdesign-miniprogram/toast/index';
import { getStudentsPromise, clearStudentsPromise } from '../../usercenter/students/edit/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    schoolList: '',
    search: true,
    inputSchool: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init()
  },

  init() {
    getAllSchool().then((detail) => {
      const allSchoolList = getSchoolList()
      let curSchoolList = []
      detail.result.forEach(element => {
        curSchoolList.push(allSchoolList[element])
      });
      this.setData({
        schoolList: curSchoolList
      })
    })
  },
  onSelected(detail) {
    const schoolData = getSelectedSchoolData()
    const { school } = detail.currentTarget.dataset
    if (school.code == schoolData.code) {
      wx.switchTab({
        url: '/pages/home/home'
      });
      return
    }
    this.changeSchool(school._id)
  },
  onSearchSchool() {
    this.setData({
      search: !this.data.search
    })
  },
  onInputValue(e) {
    this.setData({
      inputSchool: e.detail.value
    })
  },
  onJoinSchool(e) {

    if (this.data.inputSchool == getSelectedSchoolData().code) {
      wx.switchTab({
        url: '/pages/home/home'
      });
      return
    }
    const schoolMap = new Map(Object.entries(getSchoolList()))
    let isHave = false
    let id = ""
    schoolMap.forEach((item, value) => {
      if (this.data.inputSchool == item.code) {
        isHave = true
        id = item._id
      }
    });
    if (isHave) {
      this.changeSchool(id)
    }
    else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '没有此学校',
        icon: '',
        duration: 1000,
      });
    }


  },
  //切换学校
  changeSchool(id) {

    let studentList = getStudentsList()
    let curStudentInfo = ""
    studentList.forEach(element => {
      if (id == element.i_id) {
        element.default = 1
        curStudentInfo = element

      }
      else {
        element.default = 0
      }
    });
    setStudentsList(studentList)
    if (curStudentInfo && curStudentInfo != "") {
      const allSchoolList = getSchoolList()
      setSelectedStudentId(curStudentInfo._id)
      setSelectedSchoolId(curStudentInfo.i_id);
      setSelectedSchoolData(allSchoolList[curStudentInfo.i_id])
      setDefaultStudent(curStudentInfo._id).then()
      wx.switchTab({
        url: '/pages/home/home'
      });
    }
    else {
      this.waitForNewStudents()
      wx.navigateTo({ url: `/pages/usercenter/students/edit/index?schoolId=${id}` });
    }

    // })

  },
  waitForNewStudents() {
    clearStudentsPromise()
    getStudentsPromise()
      .then((newStudents) => {
        newStudents.default = 1
        console.log(newStudents)
        addStudent(newStudents).then((data) => {
          let studentList = getStudentsList()
          const schoolDate = getSchoolList()
          data.result[0].schoolName = schoolDate[data.result[0].i_id].name
          studentList.push(data.result[0])
          const allSchoolList = getSchoolList()
          setStudentsList(studentList)
          setSelectedStudentId(data.result[0]._id)
          setSelectedSchoolId(data.result[0].i_id)
          setSelectedSchoolData(allSchoolList[data.result[0].i_id])
          wx.switchTab({
            url: '/pages/home/home',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        })
      })
      .catch((e) => {
        this.setData({
          active: true
        })
        wx.navigateBack({ delta: 1 });
        if (e.message !== 'cancel') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '子女编辑发生错误',
            icon: '',
            duration: 1000,
          });
        }
      });
  },

})